<?php

/**
 * This is the model class for table "{{upper}}".
 *
 * The followings are the available columns in table '{{upper}}':
 * @property integer $upper_id
 * @property integer $user_id
 * @property string $user_name
 * @property integer $upper_user_id
 * @property string $upper_user_name
 * @property integer $upper_time
 *
 * The followings are the available model relations:
 */
class Upper extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return Upper the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{upper}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('user_id, user_name, upper_user_id, upper_user_name, upper_time', 'required'),
			array('user_id, upper_user_id, upper_time', 'numerical', 'integerOnly'=>true),
			array('user_name, upper_user_name', 'length', 'max'=>50),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('upper_id, user_id, user_name, upper_user_id, upper_user_name, upper_time', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'upper_id' => 'Upper',
			'user_id' => 'User',
			'user_name' => 'User Name',
			'upper_user_id' => 'Upper User',
			'upper_user_name' => 'Upper User Name',
			'upper_time' => 'Upper Time',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('upper_id',$this->upper_id);
		$criteria->compare('user_id',$this->user_id);
		$criteria->compare('user_name',$this->user_name,true);
		$criteria->compare('upper_user_id',$this->upper_user_id);
		$criteria->compare('upper_user_name',$this->upper_user_name,true);
		$criteria->compare('upper_time',$this->upper_time);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}

	public static function getUpper($user_id,$type='self'){
		switch($type){
			case 'self'://登录
				$self = self::getMyUpper($user_id);
				/*
				if(empty($self)){//如果没有上游
					return self::recommendUpper();
				}else//有上游 
				*/
				return $self;
				break;
			case 'other'://未登录
				return self::recommendUpper();
				break;
		}
	}
	public static function recommendUpper(){
		$criteria = new CDbCriteria(array(
			'order'=>'issue_num DESC',
			'limit'=>10,
		));
		return User::model()->findAll($criteria);
	}
	public static function getMyUpper($user_id){
		$upper = new Upper;
		$uppers = $upper->findAll("user_id=:user_id order by type ASC,upper_time DESC",array(":user_id"=>$user_id));
		if(!empty($uppers)){
			foreach($uppers as $key => $value){
				$tmp[] = $value->upper_user_id;
			}
			$userIds = implode(',',$tmp);
			if(strpos($userIds,','))
				$userTmp = User::model()->findAll("user_id in($userIds)");
			else
				$userTmp =  User::model()->find("user_id = $userIds");
			if(count($userTmp)==1){
				$user[$userTmp->user_id] = $userTmp;
			}else{
				foreach($userTmp as $key =>$v){
					$user[$v->user_id] = $v;
				}
			}
			unset($userTmp);
			foreach($uppers as $key => $up){
				$users[$up->upper_user_id]=$user[$up->upper_user_id];
				$users[$up->upper_user_id]->upperType=$up->type;

			}
			unset($user);unset($uppers);
			//dbg($users);
			return $users;
		}
		return array();
	}

	public static function delUpper($upperUserId){
			$error = array();
			$userId = Yii::app()->user->id;
			//1、删除upper表信息
			if(!Upper::model()->deleteAll('user_id=:user_id and upper_user_id=:upper_user_id',array(':user_id'=>Yii::app()->user->id,':upper_user_id'=>$upperUserId)))
				$error[]="delete upper by user_id:upper_user_id=$userId:$upper_user_id";
			//2、更新fans表信息
			if(!Fans::addFans($userId,$upperUserId,true)){//记录为过时的
				$error[] = "update fans by user_id:fans_user_id=$upper_user_id:$userId";
			}
			//3、更新user表信息
			User::model()->updateByPk(Yii::app()->user->id,array('upper_num'=>new CDbExpression('upper_num-1')));
			User::model()->updateByPk($upperUserId,array('fans_num'=>new CDbExpression('fans_num-1')));
			if(empty($error))return true;
			return $error;
	}
	public static function addUpper($upperUserId){
		//1、判断人数
		$userId = Yii::app()->user->id;
		$count = Upper::model()->count("user_id=$userId");
		//2、人数 < 10
		if($count<10){
			if(self::oprateUppper($userId,$upperUserId)) return true;
		}else{//3、人数>=10个
			if($count == 10){ //=10个
				//3.1删除一个上游（算法实现），并更新fans表和user表
				$delUid = self::getDelOneUpperId($userId);
				if($delUid != $upperUserId){
					if(is_array(Upper::delUpper($delUid))){//从upper表中删除，包括更新fans表，user表
						//删除失败
						return false;
					}else{
						//删除成功
						//3.2插入一条新记录到uper表中
						if(self::oprateUppper($userId,$upperUserId))return true;
					}
				}else
					return true;
			}else{// >10个
				//........
			}
		}
		return false;
	}
	public static function loadModelByUpperUserId($userId,$upperUserId){
		$upper = new Upper;
		$res = $upper->find("user_id=$userId and upper_user_id=$upperUserId");
		if($res !== null)return $res;
		else return $upper;
	}
	public static function oprateUppper($userId,$upperUserId){
		$successs = false;
		//2.1 操作upper表
			$upperAR = self::loadModelByUpperUserId($userId,$upperUserId);

			$upperAR->upper_time = time();
			$upperAR->type = 'user';
			if(!$upperAR->isNewRecord){//2.1.1 在upper表中已存在记录，则更新
				if($upperAR->save())$successs = true;
			}else{//2.1.2在upper表不存在记录，则插入
				$upperAR->user_id = $userId;
				$upperAR->user_name = Yii::app()->user->name;
				$upperAR->upper_user_id = $upperUserId;
				$userName = User::model()->findByPk($upperUserId);
				$upperAR->upper_user_name = $userName->user_name;
				$upperAR->type = 'recommend';
				if($upperAR->save())$successs = true;
			}
			//2.2操作fans表
			Fans::addFans($userId,$upperUserId,false);
			//2.3操作upper表
			User::model()->updateCounters(array('fans_num'=>1),"user_id=$upperUserId");
			User::model()->updateCounters(array('upper_num'=>1),"user_id=$userId");
			return $successs;
	}
	/*
	 * 删除一个上游模拟算法如下：
	 * 1、取得这个用户的所有上游UID
	 * 2、取得各个上游的七天内的发布数
	 * 3、发布数比率 = 7天发布链接数（包括发布时已存在的链接）/7
	 * 4、取得即将被删除用户ID
	 * 5、返回删除者的UID
	 */
	public static function getDelOneUpperId($userId){
		$oldUpperIds = Upper::model()->findAllByAttributes(array('user_id'=>$userId));
		if($oldUpperIds !== null){
			foreach($oldUpperIds as $handle){
				$userIds[] = $handle->upper_user_id; //No.1
			}
			if(count($userIds)){
				$tmpUid = implode(',',$userIds);
				//查找7天内$tmpUid这些用记所发布的文章数量
				$sql = "SELECT user_id,count(user_id) as issueNum FROM `nc_news` `t` WHERE `t`.`user_id` IN
($tmpUid) AND DATE_FORMAT(FROM_UNIXTIME(`post_time`),'%Y-%m-%d') > DATE_SUB(CURDATE(),INTERVAL 7 DAY) group by user_id";
				$issueNums = Yii::app()->db->createCommand($sql)->queryAll();
			}
			foreach($issueNums as $issues){
				$tmpe[$issues['user_id']] = $issues['issueNum'] / 7;
			}
			asort($tmpe,SORT_NUMERIC);
			$delUid = each($tmpe);
			return $delUid['key']; //要删除的用户ID
		}
	}
}